package org.example.onlinejudge.service;

import org.example.onlinejudge.model.Role;
import org.example.onlinejudge.model.Permission;
import org.example.onlinejudge.repository.RoleRepository;
import org.example.onlinejudge.repository.PermissionRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

/**
 * 角色服务类
 * 负责处理角色相关的业务逻辑
 */
@Service
public class RoleService {

    @Autowired
    private RoleRepository roleRepository;

    @Autowired
    private PermissionRepository permissionRepository;

    /**
     * 查找所有角色
     */
    public List<Role> findAllRoles() {
        return roleRepository.findAll();
    }

    /**
     * 根据ID查找角色
     */
    public Optional<Role> findById(Long id) {
        return roleRepository.findById(id);
    }

    /**
     * 根据角色代码查找角色
     */
    public Optional<Role> findByRoleCode(String roleCode) {
        return roleRepository.findByRoleCode(roleCode);
    }

    /**
     * 创建新角色
     */
    @Transactional
    public Role createRole(String roleCode, String roleName) {
        // 检查角色代码是否已存在
        if (roleRepository.existsByRoleCode(roleCode)) {
            throw new RuntimeException("角色代码已存在: " + roleCode);
        }

        Role role = new Role();
        role.setRoleCode(roleCode);
        role.setRoleName(roleName);
        return roleRepository.save(role);
    }

    /**
     * 更新角色信息
     */
    @Transactional
    public Role updateRole(Long id, String roleName) {
        Role role = roleRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("角色不存在"));
        
        role.setRoleName(roleName);
        return roleRepository.save(role);
    }

    /**
     * 删除角色
     */
    @Transactional
    public void deleteRole(Long id) {
        Role role = roleRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("角色不存在"));
        
        // 检查是否为系统内置角色
        if ("0".equals(role.getRoleCode()) || "1".equals(role.getRoleCode()) || "2".equals(role.getRoleCode())) {
            throw new RuntimeException("不能删除系统内置角色");
        }
        
        roleRepository.deleteById(id);
    }

    /**
     * 为角色添加权限
     */
    @Transactional
    public void addPermissionToRole(Long roleId, Long permissionId) {
        Role role = roleRepository.findById(roleId)
                .orElseThrow(() -> new RuntimeException("角色不存在"));
        
        Permission permission = permissionRepository.findById(permissionId)
                .orElseThrow(() -> new RuntimeException("权限不存在"));
        
        // 检查权限是否已存在
        if (role.getPermissions().contains(permission)) {
            throw new RuntimeException("该角色已拥有此权限");
        }
        
        role.addPermission(permission);
        roleRepository.save(role);
    }

    /**
     * 从角色移除权限
     */
    @Transactional
    public void removePermissionFromRole(Long roleId, Long permissionId) {
        Role role = roleRepository.findById(roleId)
                .orElseThrow(() -> new RuntimeException("角色不存在"));
        
        Permission permission = permissionRepository.findById(permissionId)
                .orElseThrow(() -> new RuntimeException("权限不存在"));
        
        role.removePermission(permission);
        roleRepository.save(role);
    }

    /**
     * 检查角色代码是否存在
     */
    public boolean existsByRoleCode(String roleCode) {
        return roleRepository.existsByRoleCode(roleCode);
    }
}
